package craky.util;

import java.awt.Component;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class WindowMove extends MouseAdapter
{
    private Point point;
    
    private Window window;
    
    private Component component;
    
    private boolean moveable;
    
    public WindowMove(Component component)
    {
        this.moveable = true;
        this.point = new Point(-1, -1);
        changeComponent(component);
    }
    
    public void changeComponent(Component component)
    {
        if(this.component != null)
        {
            this.component.removeMouseMotionListener(this);
            this.component.removeMouseListener(this);
        }
        
        this.component = component;
        this.window = UIUtil.getWindowFromComponent(component);
        
        if(window != null)
        {
            component.addMouseMotionListener(this);
            component.addMouseListener(this);
        }
    }
    
    public boolean isMoveable()
    {
        return moveable;
    }

    public void setMoveable(boolean moveable)
    {
        this.moveable = moveable;
    }
    
    public void mouseDragged(MouseEvent e)
    {
        boolean move = moveable;
        
        if(move && window instanceof Frame)
        {
            move = (((Frame)window).getExtendedState() & Frame.MAXIMIZED_BOTH) == 0;
        }
        
        if(move && point.x >= 0 && point.y >= 0)
        {
            int x = e.getXOnScreen() - point.x;
            int y = e.getYOnScreen() - point.y;
            window.setLocation(x, y);
        }
    }

    public void mousePressed(MouseEvent e)
    {
        if(moveable)
        {
            if(e.getButton() == MouseEvent.BUTTON1)
            {
                point.move(e.getXOnScreen() - window.getX(), e.getYOnScreen() - window.getY());
            }
            else
            {
                point.move(-1, -1);
            }
        }
    }

    public void mouseReleased(MouseEvent e)
    {
        if(moveable && e.getButton() == MouseEvent.BUTTON1)
        {
            point.move(-1, -1);
        }
    }
}